package com.lmy.springboot_quartz;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 调度器Scheduler 配置类
 * 可以只使用一个调度器，交给 IOC 容器管理
 */
@Configuration
public class SchedulerConfig {

    @Autowired
    private DataSource dataSource;

    /*
        注入任务调度器
        1.可以使用SchedulerFactory创建Scheduler，DirectSchedulerFactory在代码里定制Scheduler参数
          StdSchedulerFactory通过读取classpath下的quartz.properties配置来实例化Scheduler
     */
    @Bean
    public Scheduler scheduler() throws Exception {
        return schedulerFactoryBean().getScheduler();
    }

    /*
        SchedulerFactoryBean 可以识别classpath下Quartz的相关配置文件并读取，方便实例化Scheduler
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //设置调度器名称
        schedulerFactoryBean.setSchedulerName("cluster_scheduler");
        //注入数据源
        schedulerFactoryBean.setDataSource(dataSource);
        //配置ApplicationContextSchedulerContextKey
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("application");
        //指定配置文件
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        //指定任务执行器(线程池)
        schedulerFactoryBean.setTaskExecutor(schedulerThreadPool());
        //指定调度器执行任务的延迟时间 默认立即执行
        schedulerFactoryBean.setStartupDelay(0);
        return schedulerFactoryBean;
    }

    /*
        注入Properties用于读取Quartz配置文件
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/springboot-quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /*
        注入任务执行器(线程池对象)
     */
    @Bean
    public Executor schedulerThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //配置最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
        //配置队列容量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors());
        return executor;
    }
}
